﻿using System;
using EasyModbus;

namespace EasyModbusExample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // 创建Modbus客户端
                ModbusClient modbusClient = new ModbusClient("192.168.1.100", 502);

                // 连接到设备
                modbusClient.Connect();

                // 读取保持寄存器
                int[] holdingRegisters = modbusClient.ReadHoldingRegisters(0, 10);

                Console.WriteLine("读取保持寄存器结果:");
                for (int i = 0; i < holdingRegisters.Length; i++)
                {
                    Console.WriteLine($"寄存器 {i}: {holdingRegisters[i]}");
                }

                // 写入单个寄存器
                modbusClient.WriteSingleRegister(10, 1234);
                Console.WriteLine("已写入值1234到寄存器10");

                // 读取线圈状态
                bool[] coils = modbusClient.ReadCoils(0, 5);
                Console.WriteLine("读取线圈状态结果:");
                for (int i = 0; i < coils.Length; i++)
                {
                    Console.WriteLine($"线圈 {i}: {(coils[i] ? "ON" : "OFF")}");
                }

                // 写入单个线圈
                modbusClient.WriteSingleCoil(0, true);
                Console.WriteLine("已将线圈0设置为ON");

                // 断开连接
                modbusClient.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Modbus通信错误: {ex.Message}");
            }

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
    }
}

